<?php

namespace App\Http\Controllers\Home;

use App\Models\CompanyInfos;
use App\Models\Configs;
use App\Models\IntegralLogs;
use App\Models\Stores;
use App\Models\UserInfos;
use App\Models\Users;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * 用户登录
     * @param Request $request
     * @return bool
     */
    public function login(Request $request)
    {
        if($request->method() == 'POST'){
            $data = [
                'mobile' => (string)$request->post('mobile'),
                'password' => (string)$request->post('password'),
                'type' => (string)$request->post('type'),
                'three_id' => (string)$request->post('three_id'),
                'code' => (string)$request->post('code'),
            ];
            $user_type = (int)$request->post('user_type',2);// 1密码登陆 2手机验证码登录
            if ($user_type == 1){//验证
                $rules = ['mobile' => 'required', 'password' => 'required',];
                $msgs = ['mobile.required' => '请填写手机号码', 'password.required' => '请填写密码',];
                $validator = validator()->make($data,$rules,$msgs);
                if ($validator->fails()) {
                    return $this->writeJson(1,null,$validator->errors()->first());
                }
            }
            //存缓存
            $auth = false;
            if($user_type == 2) {
                if(empty($data['mobile']) || empty($data['code'])){
                    return $this->writeJson(1,null,'参数错误');
                }
//                //检查验证码是否正确
//                $cache = cache()->get('sms-'.$data['mobile']);
//                if(empty($cache)) return $this->writeJson(1,null,'短信验证码已过期');//过期
//                if($cache['code'] != $data['code']) return $this->writeJson(1,null,'短信验证码输入错误');
//                cache()->delete('sms-'.$data['mobile']);//删除验证码

                $user = Users::where('mobile',$data['mobile'])->first();
                if($user&&$data['mobile']){
                    \Auth::loginUsingId($user['id']);
                    $auth = true;
                }
            }else {
                $auth = auth()->guard('web')->attempt(['mobile' => $data['mobile'],'password' => $data['password']]);
            }
            //如果成功
            if ($auth) {
                $request->session()->regenerate();
                $this->clearLoginAttempts($request);
                $users = auth()->guard('web')->user();
                if($users['status'] == -1){
                    return $this->writeJson(1,null,'当前用户不存在');
                }
                if ($users['type'] == 2){//返回供应商店铺状态
                    $users['store_status'] = Stores::where('user_id',$users['id'])->value('status');
                }
                //判断当天是否签到
                $users['is_sign'] = 0;//默认未签到
                if (trim(@date('Y-m-d', strtotime($users['sign_in_at']))) == trim(date('Y-m-d'))) {
                    $users['is_sign'] = 1;//已签到
                }

                //19-9-30 by z 增加返回个人部分信息 start
                $infos_one = Users::where('id',$users['id'])->first(['nickname','mobile',]);//联系人、联系人电话
                $infos_two = UserInfos::where('user_id',$users['id'])//职位、部门、公司名称、公司类型id、公司行业id、公司规模
                            ->first(['hr_position','hr_department','company_name','company_type','company_industry','company_size']);
                $company_type = CompanyInfos::where('id',$infos_two['company_type'])->value('name');
                $company_industry = CompanyInfos::where('id',$infos_two['company_industry'])->value('name');
                $company_size = CompanyInfos::where('id',$infos_two['company_size'])->value('name');

                $users['need_infos'] = array(
                  'nickname' => !empty($infos_one['nickname']) && $infos_one['nickname'] ? $infos_one['nickname'] : '',
                  'mobile' => !empty($infos_one['mobile']) && $infos_one['mobile'] ? $infos_one['mobile'] : '',
                  'hr_position' => !empty($infos_two['hr_position']) && $infos_two['hr_position'] ? $infos_two['hr_position'] : '',
                  'hr_department' => !empty($infos_two['hr_department']) && $infos_two['hr_department'] ? $infos_two['hr_department'] : '',
                  'company_name' => !empty($infos_two['company_name']) && $infos_two['company_name'] ? $infos_two['company_name'] : '',
                  'company_type' => !empty($company_type) && $company_type ? $company_type : '',
                  'company_type_id' => !empty($infos_two['company_type']) && $infos_two['company_type'] ? $infos_two['company_type'] : 0,
                  'company_industry' => !empty($company_industry) && $company_industry ? $company_industry : '',
                  'company_industry_id' => !empty($infos_two['company_industry']) && $infos_two['company_industry'] ? $infos_two['company_industry'] : 0,
                  'company_size' => !empty($company_size) && $company_size ? $company_size : '',
                  'company_size_id' => !empty($infos_two['company_size']) && $infos_two['company_size'] ? $infos_two['company_size'] : 0
                );
                //end

                //当天第一次登陆送积分
                if (trim(@date('Y-m-d', strtotime($users['login_at']))) != trim(date('Y-m-d'))) {
                    $integral = Configs::getConfig('integral');
                    if($users['type'] == 1) {//HR登陆送积分
                        $integral_login = $integral['hr_login'];
                    }elseif ($users['type'] == 2) {//供应商登陆送积分
                        $integral_login = $integral['bus_login'];
                    }
                    Users::where('id',$users['id'])->increment('integral',$integral_login);
                    //添加日志记录
                    $integral_arr = [
                        'user_id' => $users['id'],
                        'user_name' => $users['username'],
                        'integral' => '+'.$integral_login,
                        'desc' => '每日首次登陆送积分',
                        'type' => 1,
                    ];
                    IntegralLogs::create($integral_arr);
                }
//                Users::where('id',$users['id'])->update(['login_at' => date('Y-m-d H:i:s'), 'login_ip' => $request->ip()]);
                $update = [
                    'login_ip' => $request->ip(),
                    'login_at' => Carbon::now(),
                ];
                if(isset($data['type'])){
                    switch($data['type']){
                        case 'weibo':
                            $update['weibo_id'] = $data['three_id'];
                            break;
                        case 'qq':
                            $update['qq_id'] = $data['three_id'];
                            break;
                        case 'weixin':
                            $update['wechat_id'] = $data['three_id'];
                            break;
                    }
                }
                Users::where('id',$users['id'])->update($update);
                return $this->writeJson(0,$users,'登录成功');
            }
            return $this->writeJson(1,null,'用户名或密码错误');
        }else{
            $title = '登录';
            return view('home.login.login',compact('title'));
        }
    }

    /**
     * 找回密码
     * @param Request $request
     * @return bool
     */
    public function findPass(Request $request)
    {
        if($request->method() == 'POST'){
            $mobile = (string)$request->post('mobile');
            $password = (string)$request->post('password');
            $confirmc_pass = (string)$request->post('confirmc_pass');
            $code = (string)$request->post('code');
            if(empty($mobile) || empty($password) || empty($confirmc_pass) || empty($code))  return $this->writeJson(1,null,'参数错误');
            if(!preg_match('/^((13|14|15|16|17|18|19)[0-9]\d{8})$/', $mobile)) return $this->writeJson(1,null,'请填写正确的手机号码');
            if($password !== $confirmc_pass){
                return $this->writeJson(1,null,'两次密码输入不一致,请重新输入');
            }

            $info = Users::where('mobile',$mobile)->where('status','<>',-1)->first(['id','status']);
            if(!empty($info)){
                //检查验证码是否正确
                $cache = cache()->get('sms-'.$mobile);
                if(empty($cache)) return $this->writeJson(1,null,'短信验证码已过期');//过期
                if($cache['code'] != $code) return $this->writeJson(1,null,'短信验证码输入错误');
                cache()->delete('sms-'.$mobile);//删除验证码

                Users::where('id',$info['id'])->update(['password' => bcrypt($password)]);
                return $this->writeJson(0,null, '找回成功,请重新登录');
            }else{
                return $this->writeJson(1,null, '该用户不存在');
            }
        }else{
            $title = '找回密码';
            return view('home.login.find_pass',compact('title'));
        }
    }

    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        try {
            auth()->guard('web')->logout();
            $request->session()->regenerate();
            return $this->writeJson(0, null,'退出成功');
        } catch (\Exception $e) {
            return $this->writeJson(1, null, $e->getMessage());
        }
    }

}